package com.idsmanager.zdh.web.controller.api;

import com.idsmanager.zdh.infrastructure.APIError;
import com.idsmanager.zdh.service.dto.api.UserApiResult;
import com.idsmanager.oauth.service.dto.user.UserDto;
import com.idsmanager.oauth.service.dto.user.UserEditTableDto;
import com.idsmanager.oauth.service.dto.user.UserRestTableDto;
import com.idsmanager.zdh.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@RestController
@RequestMapping(value = "/api/v1/")
public class UserRestfulController {

    @Autowired
    private UserService userService;

    /**
     * 创建用户
     * @param userRestTableDto
     * @param result
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.POST)
    @ResponseBody
    public UserApiResult userCreate(@RequestBody @Valid UserRestTableDto userRestTableDto, BindingResult result) {
        if (result.hasErrors()) {
            return new UserApiResult(APIError.PARAM_ERROR, result.getAllErrors());
        }
        return userService.createUser(userRestTableDto);
    }

    /**
     * 查询用户
     * @param username
     * @return
     */
    @RequestMapping(value = "user", method = RequestMethod.GET)
    @ResponseBody
    public UserApiResult userList(@RequestParam(value = "username") String username) {
        return userService.findByUsername(username);
    }

    /**
     * 删除用户
     * @param uuid
     * @return
     */
    @RequestMapping(value = "user/{uuid}" ,method = RequestMethod.DELETE)
    @ResponseBody
    public UserApiResult userDel(@PathVariable("uuid") String uuid) {
        return userService.delUserByGuid(uuid);
    }

    /**
     * 编辑保存用户
     * @param userEditTableDto
     * @param result
     * @return
     */
    @RequestMapping(value = "user",method = RequestMethod.PUT)
    @ResponseBody
    public UserApiResult userEdit(@RequestBody @Valid UserEditTableDto userEditTableDto, BindingResult result){
        if(result.hasErrors()){
            return new UserApiResult(APIError.PARAM_ERROR,result.getAllErrors());
        }
        return userService.restUpdateUser(userEditTableDto);
    }

}
